<template>
    <picture>
        <source 
            v-if="webp"
            ref="webpRef"
            class="lazy" 
            type="image/webp" 
            :data-srcset="src+'.webp'"
        />
        <img 
            ref="imgRef"
            alt="图片"
            class="lazy"
            :data-src="src"
            v-bind="$attrs"
        />
    </picture>
</template>

<script>
import { onMounted, onUpdated, ref } from 'vue'
import LazyLoad from "vanilla-lazyload"
import config from './config'
if (!document.lazyLoadInstance) {
    document.lazyLoadInstance = new LazyLoad(config)
}
export default {
    name: 'LazyImage',
    inheritAttrs: false,
    props: {
        src: {
            type: String,
            required: true
        },
        webp: {
            type: Boolean,
            default: true
        }
    },
    setup() {
        const webpRef = ref(null)
        const imgRef = ref(null)

        onMounted(() => {
            document.lazyLoadInstance.update()
        })

        onUpdated(() => {
            webpRef.value && LazyLoad.resetStatus(webpRef.value)
            imgRef.value && LazyLoad.resetStatus(imgRef.value)
            document.lazyLoadInstance.update()
        })

        return {
            webpRef,
            imgRef
        }
    }
}
</script>

<style>
    img:not([src]):not([srcset]) {
        visibility: hidden;
    }
</style>